<template>
	<view @tap="upEvent" :class="className">
		<view v-if="default_btn" class="">
			<button>上传</button>
		</view>
		<slot v-else-if="this.$scopedSlots['btn']" name="btn"></slot>
		<slot v-else></slot>
		
		<!-- <canvas canvas-id="watermark" class="watermark-canvas" :style="{width:watermark_width+'px',height:watermark_height+'px'}"></canvas> -->
	</view>
</template>

<script>
	import { Base64 } from './base64.min.js';
	export default {
		name: 'wzh-upload',
		props: {
			value: {
				type: [Array,String],
				default: function(){
					return ''
				}
			},
			className:  {
				type: String,
				default: 'up-box',
			},
			ossName: {
				type: String,
				default: 'hb',
			},
			dir: {
				type: String,
				default: 'newjbh/',
			},
			count: {
				type: [Number],
				default: 1
			},
			//图片image，文件file，视频video（视频可录制，只能传1个）
			fileType: {
				type: String,
				default: 'image'
			},
			sourceType: {
				type: Array,
				default: function(){
					return ['album','camera']
				}
			},
			sizeType: {
				type: Array,
				default: function(){
					return ['original', 'compressed'] //可以指定是原图还是压缩图
				}
			},
			extension: {
				type: Array,
				default: function(){
					return ['.zip','.doc'] //可以指定是原图还是压缩图
				}
			},
			upType: {
				type: String,
				default: 'oss'
			},
			camera: {
				type: String,
				default: 'back'
			},
			maxDuration: {
				type: [Number, Boolean],
				default: 60
			},
			compressed: {
				type: Boolean,
				default: true
			},
			hideLoading: {
				type: Boolean,
				default: false
			},
			tokenUrl: {
				type: String,
				default: 'https://api2.zhaojjw.cn/api/get_oss_token'
			},
			watermark: {
				type: Number,
				default: 0, // 1文字水印，2图片水印
			},
			watermarkPosition: {
				type: Number,
				default: 1, // 1左上，2，右上，3右下，4左下
			},
			watermarkSize: {
				type: [Array,Number],
				default: function(){
					return 24; // 文字水印为字体大小，图片水印为宽高
				}
			},
			watermarkText: {
				type: String,
				default: '唯宅汇'
			},
			watermarkColor: {
				type: String,
				default: 'FFFFFF'
			},
			watermarkPadding: {
				type: Array,
				default: function(){
					return [20,20]; // 上下边距和左右边距
				}
			},
			disable: {
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				default_btn:false,
				file_list:[],
				file:'',
				shooseCount:0,//已经选择文件数量
				upCount:0,
				tastList:{},
				
				watermark_width:100,
				watermark_height:100,
				watermark_position:()=>{
					var g = {1:"center",1:"nw",12:"north",2:"ne",23:"east",3:"se",34:"south",4:"sw",41:"west"};
					return g[this.watermarkPosition]||"nw";
				}
			};
		},
		watch:{
			value(n,o){
				var new_value = typeof(n)=='string'?[n]:n
				this.file_list = new_value||[];
			}
		},
		mounted() {
			if(!this.$scopedSlots['btn']&&!this.$scopedSlots['default']) this.default_btn = true
			var new_value = typeof(this.value)=='string'?[this.value]:this.value
			this.file_list = new_value||[];
		},
		methods:{
			upEvent(){
				console.log(111111)
				if(this.disable) return
				var fileCount = this.count - this.file_list.length
				if(this.fileType == 'image'){
					uni.chooseImage({
					    count: fileCount, //默认9
					    sizeType: this.sizeType, //可以指定是原图还是压缩图，默认二者都有
					    sourceType: this.sourceType,
					    success: async(res)=>{
							let tempFilePaths = res.tempFilePaths;
							!this.hideLoading&&uni.showLoading({
								title:`上传中${this.upCount}/${this.shooseCount}`,
							})
							// if(this.watermark){
							// 	let p = []
							// 	for(var i =0;i<tempFilePaths.length;i++){
							// 		p.push(this.buildWatermark(tempFilePaths[i]));
							// 	}
							// 	await Promise.all(p).then((res)=>{
							// 		console.log(res)
							// 		tempFilePaths = res
							// 	});
							// }
					        this.upLoad(tempFilePaths);
					    }
					});
				}
				else if(this.fileType == 'file'){
					uni.chooseFile({
						count: fileCount, //默认100
						extension: this.extension,
					    success: (res)=>{
					        this.upLoad(res.tempFilePaths);
					    }
					});
				}
				else if(this.fileType == 'video'){
					uni.chooseVideo({
						count: fileCount,
						sourceType: this.sourceType,
						extension: this.extension,
						success: (res)=>{
							this.upLoad([res.tempFilePath]);
						}
					});
				}
			},
			//制作图片水印
			// buildWatermark(tempFilePaths){
			// 	return new Promise((resolve, reject)=>{
			// 		uni.getImageInfo({
			// 			src:tempFilePaths,
			// 			success:(res)=>{
			// 				let ctx = uni.createCanvasContext('watermark', this);
			// 				this.watermark_width = res.width
			// 				this.watermark_height =res.height
			// 				setTimeout(()=>{
			// 					ctx.drawImage(tempFilePaths,0,0)
								
			// 					// 文字水印
			// 					let x,y
			// 					console.log(this.watermark)
			// 					if(this.watermark == 1){
			// 						ctx.setTextBaseline('middle')
			// 						// 左上
			// 						if(this.watermarkPosition == 1){
			// 							ctx.textAlign = 'left';
			// 							x = this.watermarkPadding[3]
			// 							y = this.watermarkPadding[0]
			// 						}
			// 						// 右上
			// 						else if(this.watermarkPosition == 2){
			// 							ctx.textAlign = 'right';
			// 							x = this.watermark_width - this.watermarkPadding[1]
			// 							y = this.watermarkPadding[0]
			// 						}
			// 						// 右下
			// 						else if(this.watermarkPosition == 3){
			// 							ctx.textAlign = 'right';
			// 							x = this.watermark_width - this.watermarkPadding[1]
			// 							y = this.watermark_height - this.watermarkPadding[2]
			// 						}
			// 						// 左下
			// 						else if(this.watermarkPosition == 4){
			// 							ctx.textAlign = 'left';
			// 							x = this.watermarkPadding[3]
			// 							y = this.watermark_height - this.watermarkPadding[2]
			// 						}
			// 						ctx.setFillStyle(this.watermarkColor)
			// 						ctx.setFontSize(this.watermarkSize)
			// 						ctx.fillText(this.watermarkText, x, y)
									
			// 					}
			// 					ctx.draw(false,()=>{
			// 						uni.canvasToTempFilePath({
			// 							fileType: 'jpg',
			// 							quality: .5,
			// 							canvasId: 'watermark',
			// 							success: (res)=>{
			// 								resolve(res.tempFilePath)
			// 								// resolve(this.dataURLtoBlob(res.tempFilePath))
			// 							} 
			// 						})
			// 					})
			// 				},200)
			// 			}
			// 		})
			// 	});
			// },
			ossWatermark(key,ossConfig){
				return new Promise((resolve, reject)=>{
					let water_key = key + "_water"
					let text = Base64.encode(this.watermarkText);
					text = text.replace(/\+/g,"-")
					text = text.replace(/\//g,"_")
					text = text.replace(/\=/g,"-")
					uni.downloadFile({
						url:ossConfig.domain+"/"+key + `?x-oss-process=image/watermark,text_${text},color_${this.watermarkColor},shadow_10,t_100,g_${this.watermark_position()},x_${this.watermarkPadding[1]},y_${this.watermarkPadding[0]},size_${this.watermarkSize}`,
						success:(res)=>{
							uni.uploadFile({
								url: ossConfig.domain, //仅为示例，非真实的接口地址
								filePath: res.tempFilePath,
								name: 'file',
								formData: {
									'OSSAccessKeyId': ossConfig.accessid,
									'policy': ossConfig.policy,
									'signature': ossConfig.signature,
									'expire': ossConfig.expire,
									'success_action_status': '200',
									'key': water_key,
								},
								success: ()=>{
									resolve(water_key)
								},
								fail: ()=>{
									reject(key);
								}
							})
						},
						fail: ()=>{
							reject(key);
						}
					})
				});
			},
			dataURLtoBlob(dataurl) {
				var arr = dataurl.split(',');
				//注意base64的最后面中括号和引号是不转译的   
				var _arr = arr[1].substring(0,arr[1].length-2);
				var mime = arr[0].match(/:(.*?);/)[1],
				bstr =atob(_arr),
				n = bstr.length,
				u8arr = new Uint8Array(n);
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n);
				}
				return new Blob([u8arr], {
					type: mime
				});
			},
			upLoad(tempFilePaths){
				this.shooseCount = tempFilePaths.length
				this.upCount = 0
				if(this.upType == 'oss'){
					this.ossUpLoad(tempFilePaths)
				}
			},
			ossUpLoad(tempFilePaths){
				uni.request({
					url:this.tokenUrl,
					data:{
						name: this.ossName,
						dir: this.dir,
					},
					success:(res)=>{
						let ossConfig = res.data.result
						this.tastList = {}
						for(var i in tempFilePaths){
							let file = tempFilePaths[i]
							var key = (ossConfig.dir||"")+this.buildFilename();
							
							let text = Base64.encode(this.watermarkText);
							this.tastList[i] = uni.uploadFile({
								url: ossConfig.domain, //仅为示例，非真实的接口地址
								filePath: file,
								name: 'file',
								formData: {
									'OSSAccessKeyId': ossConfig.accessid,
									'policy': ossConfig.policy,
									'signature': ossConfig.signature,
									'expire': ossConfig.expire,
									'success_action_status': '200',
									'key': key,
								},
								success: function(){
									var _key = key
									return async(res)=>{
										if(this.file_list.length>=this.count){
											this.file_list.splice(this.count-2,(this.file_list.length-this.count+1))
										}
										if(this.watermark){
											await this.ossWatermark(_key,ossConfig).then((res)=>{
												_key = res
											})
										}
										var file_path = ossConfig.domain+"/"+_key
										this.file_list.push(file_path)
										this.$emit('onUpload',file_path)
										
										this.upCount++
										!this.hideLoading&&uni.showLoading({
											title:`上传中${this.upCount}/${this.shooseCount}`,
										})
										if(this.upCount >= this.shooseCount){
											this.complete()
										}
									}
								}.bind(this)(),
								fail: (res) => {
									console.log(res,this.upCount,this.shooseCount)
									this.upCount++
									if(this.upCount >= this.shooseCount){
										this.complete()
									}
								}
							});
							console.log(this.tastList)
							this.tastList[i].onProgressUpdate(function(){
								var index = i;
								return (res) => {
									this.$emit('onProgress',index,res)
								};
							}.bind(this)());
						}
					}
				});
			},
			complete(){
				!this.hideLoading&&uni.hideLoading()
				var res = this.count>1?this.file_list:(this.file_list[0]||'')
				this.$emit('onComplete',res)
				this.$emit('update:value', res)
			},
			buildFilename(){
				var d = new Date();
				return ""+d.getFullYear()+d.getMonth()+d.getDate()+d.getMinutes()+d.getSeconds()+(Math.floor(Math.random()*(9999-1000))+1000);
			}
		}
	}
</script>

<style lang="less">
	.up-box{
		display: inherit;
	}
	

.watermark-canvas{
	position: fixed;
	left: 200%;
	opacity: 0;
}
</style>
